package com.javalong.affairs.listener;

import java.io.File;
import java.lang.reflect.Type;

import org.apache.commons.io.FileUtils;

import android.util.Base64;

import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.javalong.affairs.model.ResponseData;

public class BaseResponseListener implements Response.Listener<String> {
	private final static Type responseDataType = new TypeToken<ResponseData>() {
	}.getType();

	protected FailedListener failedListener;
	protected Type type;

	public BaseResponseListener(Type type) {
		this.failedListener = new DefaultFailedListener();
		this.type = type;
	}

	public BaseResponseListener(FailedListener failedListener, Type type) {
		this.failedListener = failedListener;
		this.type = type;
	}

	@Override
	public void onResponse(String jsonStr) {
		// jsonStr = new String(Base64.decode(jsonStr, Base64.DEFAULT));
		ResponseData msgBean = getMsgBean(jsonStr);
		if (msgBean != null && msgBean.errorCode == 0) {
			if (msgBean.data != null) {
				if (type != null) {
					try {
						Gson gson = new Gson();
						onSuccess(gson
								.fromJson(gson.toJson(msgBean.data), type));
					} catch (Exception e) {
						e.printStackTrace();
						onSuccess(null);
					}
				} else {
					onSuccess(null);
				}
			}
		} else {
			failedListener.onFailed(msgBean);
		}
	}

	public void onSuccess(Object obj) {
	}

	private ResponseData getMsgBean(String jsonString) {
		try {
			ResponseData msgBean = new Gson().fromJson(jsonString,
					responseDataType);
			return msgBean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
